import fs from 'fs';
import axios from 'axios';
import { appid, sourceUrl, customeAppId, projectName } from '../src/utils/serviceSwitching.js';
import currentEnv from './currentEnv';

const path = require('path');

const rootPathy = path.resolve(__dirname, '../');
const projectConfigTemplageFile = rootPathy + '/configure/template/project.config.json';
const projectConfigFile = rootPathy + '/project.config.json';
const customStyleFile = rootPathy + '/src/common/css/customeStyle.scss';
const envFile = rootPathy + '/configure/currentEnv.js';
const indexHtmlTemplateFile = rootPathy + '/configure/template/index.html';
const indexHtmlFile = rootPathy + '/src/index.html';

function requireUncached(module) {
  delete require.cache[require.resolve(module)];
  return require(module);
}

// 项目配置文件
const projectConfig = () => {
  try {
    const fileData = fs.readFileSync(projectConfigTemplageFile, 'utf8');
    let data = JSON.parse(fileData);
    data.appid = appid;
    data.description = projectName;
    fs.writeFileSync(projectConfigFile, JSON.stringify(data, null, 2));
    console.log('项目配置文件 -- ok');
  } catch (error) {
    console.log('项目配置文件 -- fail');
  }
};
// 样式配置
const getStyle = async () => {
  try {
    const res = await axios.get(
      `${sourceUrl}/ht-fine-merchant/host/${customeAppId}/customeStyle.css`,
    );
    const regex = /customePageStyle {\s*color: (?<pageColor>#[A-Za-z0-9]{6})/gm;
    const pageColor = regex.exec(res.data).groups.pageColor;

    const { navBarStyle } = requireUncached('./currentEnv');
    // 小程序需要添加顶部样式
    const str = `${res.data}

.customNavigationBarStyle {
  background-color: ${navBarStyle.navigationBarBackgroundColor};
  color: ${navBarStyle.navigationBarTextStyle};
}`;

    if (currentEnv.platform === 'h5') {
      // 替换全局样式文件 /src/common/css/customeStyle.scss
      // h5 使用动态获取的样式文件
      fs.writeFileSync(customStyleFile, '');
    } else {
      // 替换全局样式文件 /src/common/css/customeStyle.scss
      // 小程序编译器获取样式并替换
      fs.writeFileSync(customStyleFile, str);
    }

    // 替换配置文件中的颜色
    const serviceSwitchingData = fs.readFileSync(envFile, 'utf8');
    let newColor = currentEnv.platform === 'h5' ? 'currentColor' : pageColor;
    const newConfig = serviceSwitchingData.replace('[customeColor]', newColor);
    fs.writeFileSync(envFile, newConfig);

    console.log('样式配置 -- ok');
  } catch (e) {
    console.log('配置样式失败  -- fail', e);
  }
};
projectConfig();
getStyle();
require('./replace_lpk.js');
